package com.imooc.controller;


import com.imooc.pojo.Bgm;
import com.imooc.service.BgmService;
import com.imooc.utils.FileUtils;
import com.imooc.utils.IMoocJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@Api(value = "背景音乐相关", tags = {"背景音乐相关的接口"})
@RequestMapping("/bgm")
public class BgmController extends BaseController {
    @Autowired
    private BgmService bgmService;

    @Value("${com.imooc.fileSpace}")
    private String fileSpace;

    @PostMapping("/list")
    @ApiOperation(value = "背景音乐列表", notes = "获取背景音乐的列表")
    public IMoocJSONResult list() {
        // List<Bgm> bgmList = bgmService.list();
        return IMoocJSONResult.ok(bgmService.list());
    }


    @PostMapping("/uploadBgm")
    @ApiOperation(value = "上传背景音乐", notes = "上传背景音乐")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bgmName", value = "bgmName", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "bgmAuthor", value = "bgmAuthor", required = true, dataType = "String", paramType = "form"),
    })
    public IMoocJSONResult uploadBgm(
            String bgmName,
            String bgmAuthor,
            @RequestParam("bgm") MultipartFile[] files) throws IOException {
        //判断传递的文件是不是空的
        if (files == null || files.length == 0) {
            return IMoocJSONResult.errorMsg("请选择文件 ");
        }
        //去除空格
        bgmName = bgmName.replace(" ", "");
        //数据库相对路径
        String uploadPathDB = "/bgm";
        uploadPathDB = FileUtils.saveFile(files, fileSpace, uploadPathDB, bgmName);
        //保存到数据库中
        Bgm bgm = new Bgm();
        bgm.setName(bgmName);
        bgm.setPath(uploadPathDB);
        bgm.setAuthor(bgmAuthor);

        bgmService.saveBgm(bgm);

        return IMoocJSONResult.ok(uploadPathDB);
    }

}
